/**
 * 地理分析工具类
 * 使用 turf.js 进行地理空间分析
 */

/**
 * 检查点是否在多边形内
 * @param {Array} polygonPoints - 多边形点数组，格式: [{lng, lat}, ...]
 * @param {Array} testPoints - 测试点数组，格式: [{id, lng, lat}, ...]
 * @returns {Promise<Object>} 分析结果
 */
export const checkPointsInPolygon = async (polygonPoints, testPoints) => {
  try {
    // 动态导入 turf.js
    const turf = await import('@turf/turf')
    
    console.log('开始分析点位置，多边形点数:', polygonPoints.length)
    
    // 将多边形点转换为 turf 格式
    const polygonCoordinates = polygonPoints.map(point => [point.lng, point.lat])
    console.log('转换后的多边形坐标:', polygonCoordinates)
    
    // 创建 turf 多边形
    const polygon = turf.polygon([polygonCoordinates])
    console.log('创建的 turf 多边形:', polygon)
    
    // 检查每个测试点是否在多边形内
    const pointsInPolygon = []
    const pointsOutsidePolygon = []
    
    testPoints.forEach((point, index) => {
      // 创建 turf 点
      const turfPoint = turf.point([point.lng, point.lat])
      
      // 判断点是否在多边形内
      const isInside = turf.booleanPointInPolygon(turfPoint, polygon)
      
      console.log(`点 ${index + 1} (${point.lng}, ${point.lat}): ${isInside ? '在区域内' : '在区域外'}`)
      
      if (isInside) {
        pointsInPolygon.push(point)
      } else {
        pointsOutsidePolygon.push(point)
      }
    })
    
    // 构建结果对象
    const result = {
      polygonCoordinates,
      pointsInPolygon,
      pointsOutsidePolygon,
      totalPoints: testPoints.length,
      inCount: pointsInPolygon.length,
      outCount: pointsOutsidePolygon.length,
      success: true
    }
    
    // 输出结果
    console.log('=== 点位置分析结果 ===')
    console.log('绘制的多边形坐标:', polygonCoordinates)
    console.log('在多边形内的点:', pointsInPolygon)
    console.log('在多边形外的点:', pointsOutsidePolygon)
    console.log(`总计: ${testPoints.length} 个点，其中 ${pointsInPolygon.length} 个在区域内，${pointsOutsidePolygon.length} 个在区域外`)
    
    return result
    
  } catch (error) {
    console.error('turf.js 分析出错:', error)
    return {
      success: false,
      error: error.message,
      polygonCoordinates: [],
      pointsInPolygon: [],
      pointsOutsidePolygon: [],
      totalPoints: testPoints.length,
      inCount: 0,
      outCount: 0
    }
  }
}

/**
 * 检查绘制的线是否形成闭合区域
 * @param {Array} linePoints - 线点数组
 * @param {number} threshold - 闭合阈值，默认 10
 * @returns {Object} 闭合检测结果
 */
export const checkLineClosure = (linePoints, threshold = 10) => {
  if (!linePoints || linePoints.length < 3) {
    return {
      isClosed: false,
      reason: '点数不足，至少需要3个点'
    }
  }
  
  const firstPoint = linePoints[0]
  const lastPoint = linePoints[linePoints.length - 1]
  
  // 计算首尾点距离
  const dx = firstPoint.lng - lastPoint.lng
  const dy = firstPoint.lat - lastPoint.lat
  const distance = Math.sqrt(dx * dx + dy * dy)
  
  const isClosed = distance <= threshold
  
  console.log('闭合检测:', { 
    firstPoint, 
    lastPoint, 
    distance, 
    threshold, 
    isClosed 
  })
  
  return {
    isClosed,
    distance,
    threshold,
    firstPoint,
    lastPoint,
    reason: isClosed ? '形成闭合区域' : '未形成闭合区域'
  }
}

/**
 * 生成分析结果消息
 * @param {Object} analysisResult - 分析结果对象
 * @returns {string} 格式化的消息
 */
export const generateAnalysisMessage = (analysisResult) => {
  if (!analysisResult.success) {
    return `分析失败: ${analysisResult.error}`
  }
  
  return `分析完成: ${analysisResult.inCount} 个点在区域内，${analysisResult.outCount} 个点在区域外`
}

/**
 * 获取详细的分析报告
 * @param {Object} analysisResult - 分析结果对象
 * @returns {Object} 详细报告
 */
export const getDetailedReport = (analysisResult) => {
  if (!analysisResult.success) {
    return {
      title: '分析失败',
      message: analysisResult.error,
      type: 'error'
    }
  }
  
  return {
    title: '点位置分析报告',
    message: generateAnalysisMessage(analysisResult),
    type: 'success',
    details: {
      totalPoints: analysisResult.totalPoints,
      inPolygon: analysisResult.inCount,
      outsidePolygon: analysisResult.outCount,
      inPoints: analysisResult.pointsInPolygon,
      outPoints: analysisResult.pointsOutsidePolygon
    }
  }
} 